package com.atguigu.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.PayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: fd
 * @Date 2021/10/11 17:01
 * @Description: 支付控制层
 */
@Slf4j
@Controller
public class PayWebController {

	private final AlipayTemplate alipayTemplate;

	private final OrderService orderService;

	public PayWebController(AlipayTemplate alipayTemplate, OrderService orderService) {
		this.alipayTemplate = alipayTemplate;
		this.orderService = orderService;
	}

	/**
	 * 用户下单:支付宝支付
	 * 1、让支付页让浏览器展示
	 * 2、支付成功以后，跳转到用户的订单列表页
	 * @param orderSn
	 * @return
	 * @throws AlipayApiException
	 */
	@ResponseBody
	@GetMapping(value = "/aliPayOrder",produces = "text/html")
	public String aliPayOrder(@RequestParam("orderSn") String orderSn) throws AlipayApiException {
		PayVo payVo = orderService.getOrderPay(orderSn);
		String pay = alipayTemplate.pay(payVo);
		log.info("调用支付宝支付生成的订单pay={}",pay);
		return pay;
	}

	/**
	 * 微信支付
	 * @author fd
	 * @date 2021/10/12 15:34
	 * @param orderSn
	 * @param model
	 * @return java.lang.String
	 */
//	@GetMapping(value = "/weixinPayOrder")
//	public String weixinPayOrder(@RequestParam("orderSn") String orderSn, Model model) {
//		OrderEntity orderInfo = orderService.getOrderByOrderSn(orderSn);
//		if (orderInfo == null) {
//			throw new RuntimeException("订单不存在");
//		}
//
//		PayRequest request = new PayRequest();
//		request.setOrderName("4559066-最好的支付sdk");
//		request.setOrderId(orderInfo.getOrderSn());
//		request.setOrderAmount(0.01);
//		request.setPayTypeEnum(WXPAY_NATIVE);
//
//		PayResponse payResponse = bestPayService.pay(request);
//		payResponse.setOrderId(orderInfo.getOrderSn());
//		log.info("发起支付 response={}", payResponse);
//		//传入前台的二维码路径生成支付二维码
//		model.addAttribute("codeUrl",payResponse.getCodeUrl());
//		model.addAttribute("orderId",payResponse.getOrderId());
//		model.addAttribute("returnUrl",wxPayConfig.getReturnUrl());
//
//		return "createForWxNative";
//	}
}
